//=========================================================================
// Copyright (C) 2024 The C++ Component Model(COMO) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================

#ifndef __VOTER_MESSAGE_H__
#define __VOTER_MESSAGE_H__

#include <stdint.h>
#include <string.h>

#ifdef __cplusplus
extern "C"
{
#endif

/**
 * VoterMessage, 包格式，客户端和服务器端通过这个包交换数据
 * 包大小为38(包含预留buf)或36(不包含预留buf)
 **/
#pragma pack(1)
typedef struct tagVoterMessage {
/* 0*/    int32_t  len;                // 消息长度, 含包头
/* 4*/    uint32_t crc32;              // CRC 校验值，从 type 开始及后面的内容
/* 8*/    char     type;               // 消息类型
/* 9*/    char     reservedChars[3];   // 幻数, magicNumber: "TJ\0"
/*12*/    uint64_t idTransaction;      // 事务ID, ID of Transaction
/*20*/    uint64_t lamportClock;       // 分布式时钟, LamportClock
/*28*/    int64_t  data;               // 数据
/*36*/    char     buf[2];
} VoterMessage;
#pragma pack()

// 2 = sizeof(message->buf)
#define VoterMessage_HEAD_LEN   (sizeof(VoterMessage) - 2)

typedef enum tagVoterMessageType {
    VOTER_NULL               = 0,
    VOTER_SYNC_CLOCK         = 1,      // 同步时钟
    VOTER_CMD_MONITOR        = 2,      // 获得监测信息
    VOTER_CMD_START_NEW      = 3,      // 开始一次新的表决
    VOTER_CMD_VOTING_DATA    = 4,      // 上报表决数据
    VOTER_CMD_VOTING_BIGDATA = 5,      // 上报表决大数据
    VOTER_CMD_VOTE           = 6,      // 请求表决
    VOTER_RESULT_RAW         = 7,      // 结果，原始数据
    VOTER_RESULT_FAIL        = 8,      // 结果，投票失败数据
    VOTER_RESULT_NOID        = 9,      // 结果，没找到你要投票的事务
} VoterMessageType;

extern const char* VoterMessageTypeNames[];

const char* GetVoterMessageTypeName(int value);

/**
 * BoxVoterMessage
 */
VoterMessage *BoxVoterMessage(char *buffer, int32_t bufSize, char type,
                              uint64_t idTransaction, uint64_t lamportClock,
                              int64_t data, char *str, int32_t rawDataSize);

/**
 * UnBox VoterMessage
 */
VoterMessage *CheckBoxVoterMessage(VoterMessage *box, int bufSize);

#ifdef __cplusplus
}
#endif

#endif // __VOTER_MESSAGE_H__
